﻿using AutoMapper;
using MediatR;
using Medical.Api.Read.Application.Command.RecyclingCleaning;
using Medical.Api.Read.Dto.RecyclingCleaning;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.EntityFrameworkCore;

namespace Medical.Api.Read.Application.Handler.RecyclingCleaning
{
    /// <summary>
    /// 获取物品信息的命令处理
    /// </summary>
    public class GetitemTableInfoCommandHandlter : IRequestHandler<GetitemTableInfoCommand, ApiResult<List<ItemtableDtos>>>
    {

        /// <summary>
        /// 物品仓储
        /// </summary>
        private readonly IBaseRepository<ItemTable> itemTableRepository;
        /// <summary>
        /// automapper
        /// </summary>
        private readonly IMapper mapper;



        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="itemTableRepository">物品表仓储</param>
        /// <param name="mapper">automapper</param>
        public GetitemTableInfoCommandHandlter(IBaseRepository<ItemTable> itemTableRepository,IMapper mapper)
        {
            this.itemTableRepository = itemTableRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理获取物品信息的请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>物品信息列表</returns>
        public async Task<ApiResult<List<ItemtableDtos>>> Handle(GetitemTableInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {


                // 根据回收申请不为0查询所有数据
                var query = itemTableRepository.GetAll()
                    .Where(x => x.IsDeleted != true && x.RecyclingId != 0);

                // 如果提供了物品条码，则按条码过滤
                if (!string.IsNullOrWhiteSpace(request.ItemCode))
                {
                    query = query.Where(item => item.ItemCode.Contains(request.ItemCode));
                }

                // 执行查询并返回结果
                var items = query.OrderByDescending(x=>x.CreateTime).ToList();

          

                return new ApiResult<List<ItemtableDtos>>
                {
                    Code = ApiEnums.Success,
                    Data = mapper.Map<List<ItemtableDtos>>(items),
                    Msg = "获取物品信息成功"
                };
            }
            catch (Exception ex)
            {
               
                return new ApiResult<List<ItemtableDtos>>
                {
                    Code = ApiEnums.Error,
                    Data = new List<ItemtableDtos>(),
                    Msg = $"获取物品信息失败: {ex.Message}"
                };
            }
        }
    }
}
